﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using NetWing.Common.JSON;
using NetWing.BPM.Core;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Data.SqlServer;
using NetWing.Common.Data;
using System.Data.Linq;
using NetWing.Common;

namespace NetWing.Model
{
    public class flow
    {
        /// <summary>
        /// 创建一个工作流实例
        /// </summary>
        /// <returns></returns>
        public static bool CreateInstance(JObject obj)
        {
            SqlTransaction ctran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            var flowInstance = obj.ToObject<FlowInstanceModel>();

            //获取提交的表单数据
            var frmdata = new JObject();
            foreach (var property in obj.Properties().Where(U => U.Name.Contains("data_")))
            {
                frmdata[property.Name] = property.Value;
            }

            //flowInstance.FrmData = JsonHelper.Instance.Serialize(frmdata);
            flowInstance.FrmData = NetWing.Common.JSON.JSONhelper.Serialize(frmdata);

            //创建运行实例
            var wfruntime = new FlowRuntime(flowInstance);

            #region 根据运行实例改变当前节点状态
            flowInstance.InstanceSchemeId = int.Parse(obj["SchemeId"].ToString());//流程实例模板ID
            flowInstance.ActivityId = wfruntime.runtimeModel.nextNodeId;
            flowInstance.ActivityType = wfruntime.GetNextNodeType();//-1无法运行,0会签开始,1会签结束,2一般节点,4流程运行结束
            flowInstance.ActivityName = wfruntime.runtimeModel.nextNode.name;
            flowInstance.PreviousId = wfruntime.runtimeModel.currentNodeId;
            flowInstance.CreateUserId = int.Parse(SysVisitor.Instance.cookiesUserId);
            flowInstance.CreateUserName = SysVisitor.Instance.cookiesUserName;
            flowInstance.MakerList = (wfruntime.GetNextNodeType() != 4 ? GetMakerList(wfruntime) : "");//当前节点可执行的人信息
            flowInstance.IsFinish = (wfruntime.GetNextNodeType() == 4 ? 1 : 0);
            flowInstance.CreateDate = DateTime.Now;
            #endregion
            try
            {
                int flowInstanceKeyId = DbUtils.tranInsert(flowInstance, ctran);//创建工作流实例 并返回keyid

                #region 流程操作记录
                FlowInstanceOperationHistoryModel processOperationHistoryEntity = new FlowInstanceOperationHistoryModel
                {
                    InstanceId = flowInstanceKeyId,
                    CreateUserId = flowInstance.CreateUserId,
                    CreateUserName = flowInstance.CreateUserName,
                    CreateDate = DateTime.Now,
                    VerificationFinally = "1",//开单默认同意(或已处理/已经完成)
                    VerificationOpinion= "创建了一个流程",
                    NodeName="创建",
                    Content = "【创建】"
                              + flowInstance.CreateUserName
                              + "创建了一个流程进程【"
                              + flowInstance.Code + "/"
                              + flowInstance.CustomName + "】"
                };
                DbUtils.tranInsert(processOperationHistoryEntity, ctran);//提交流程操作记录

                #endregion
                #region 流转记录

                FlowInstanceTransitionHistoryModel processTransitionHistoryEntity = new FlowInstanceTransitionHistoryModel
                {
                    InstanceId = flowInstanceKeyId,
                    FromNodeId = wfruntime.runtimeModel.currentNodeId,
                    FromNodeName = wfruntime.runtimeModel.currentNode.name,
                    FromNodeType = wfruntime.runtimeModel.currentNodeType,
                    ToNodeId = wfruntime.runtimeModel.nextNodeId,
                    ToNodeName = wfruntime.runtimeModel.nextNode.name,
                    ToNodeType = wfruntime.runtimeModel.nextNodeType,
                    IsFinish = wfruntime.runtimeModel.nextNodeType == 4 ? 1 : 0,
                    TransitionSate = 0,
                    CreateUserId = flowInstance.CreateUserId,
                    CreateDate = DateTime.Now,//创建时间
                    CreateUserName = flowInstance.CreateUserName
                };
                DbUtils.tranInsert(processTransitionHistoryEntity, ctran);//提交流程操作记录
                #endregion


                ctran.Commit();//提交事务

                #region 微信催单

                string[] codes = flowInstance.Code.Split('_');
                //string[] names = flowInstance.CustomName.Split('_');

                sendWxContent wxc = new sendWxContent();
                wxc.first = flowInstance.CustomName + "通知";
                wxc.keyword1 = "JYD" + codes[0];
                wxc.keyword2 = wfruntime.runtimeModel.currentNode.name + ",下一步:" + wfruntime.runtimeModel.nextNode.name;//当前流程
                wxc.keyword3 = DateTime.Now.ToString();
                wxc.remark = "流程创建人:" + flowInstance.CreateUserName;
                wxc.userids = flowInstance.MakerList;
                wxc.viewUrl = NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/QRCodeView.aspx?keyid=" + codes[1] + "";
                sendWeixin.sendWX(wxc);//发送微信

                #endregion
            }
            catch (Exception er)
            {
                ctran.Rollback();//事务回滚
                throw;
            }





            return true;
        }

        /// <summary>
        /// 寻找该节点执行人
        /// </summary>
        /// <param name="wfruntime"></param>
        /// <returns></returns>
        private static string GetMakerList(FlowRuntime wfruntime)
        {
            string makerList = "";
            if (wfruntime.runtimeModel.nextNodeId == "-1")
            {
                throw (new Exception("无法寻找到下一个节点"));
            }
            if (wfruntime.runtimeModel.nextNodeType == 0)//如果是会签节点
            {
                List<string> _nodelist = wfruntime.GetCountersigningNodeIdList(wfruntime.runtimeModel.currentNodeId);
                string _makerList = "";
                foreach (string item in _nodelist)
                {
                    _makerList = flow.GetMakerList(wfruntime.runtimeModel.nodes[item], (wfruntime.runtimeModel.flowInstanceId).ToString());
                    if (_makerList == "-1")
                    {
                        throw (new Exception("无法寻找到会签节点的审核者,请查看流程设计是否有问题!"));
                    }
                    if (_makerList == "1")
                    {
                        throw (new Exception("会签节点的审核者不能为所有人,请查看流程设计是否有问题!"));
                    }
                    if (makerList != "")
                    {
                        makerList += ",";
                    }
                    makerList += _makerList;
                }
            }
            else
            {
                makerList = flow.GetMakerList(wfruntime.runtimeModel.nextNode, (wfruntime.runtimeModel.flowInstanceId).ToString());
                if (makerList == "-1")
                {
                    throw (new Exception("无法寻找到节点的审核者,请查看流程设计是否有问题!"));
                }
            }

            return makerList;
        }
        /// <summary>
        /// 寻找该节点执行人
        /// </summary>
        /// <param name="node"></param>
        /// <param name="processId">必须是字符格式，应为是时间戳</param>
        /// <returns></returns>
        private static string GetMakerList(FlowNode node, string processId)
        {
            string makerList = "";

            if (node.setInfo == null)
            {
                makerList = "-1";
            }
            else
            {
                if (node.setInfo.NodeDesignate == Setinfo.ALL_USER)//所有成员
                {
                    makerList = "1";
                }
                else if (node.setInfo.NodeDesignate == Setinfo.SPECIAL_USER)//指定成员
                {
                    makerList = NetWing.Common.StringHelper.ArrayToString(node.setInfo.NodeDesignateData.users, makerList);

                    if (makerList == "")
                    {
                        makerList = "-1";
                    }
                }
                else if (node.setInfo.NodeDesignate == Setinfo.SPECIAL_ROLE)  //指定角色
                {
                    //var users = RevelanceManagerApp.Get(Define.USERROLE, false, node.setInfo.NodeDesignateData.roles);
                    //makerList = GenericHelpers.ArrayToString(users, makerList);

                    if (makerList == "")
                    {
                        makerList = "-1";
                    }
                }
            }
            return makerList;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public TableData Load(req req)
        {
            DataContext db = new DataContext(SqlEasy.connString);            Table<FlowInstanceModel> fi = db.GetTable<FlowInstanceModel>();            Table<FlowInstanceOperationHistoryModel> fo = db.GetTable<FlowInstanceOperationHistoryModel>();            int pageSize = req.pageSize;
            int pageNum = req.pageNum;

            //todo:待办/已办/我的
            var result = new TableData(); //datatable数据返回
            var user = SysVisitor.Instance.cookiesUserId;

            if (req.type == "wait")   //待办事项
            {
                //result.count = UnitWork.Find<FlowInstance>(u => u.MakerList == "1" || u.MakerList.Contains(user.User.Id)).Count();
                result.count = fi.Count(u => u.MakerList == "1" || u.MakerList.Contains(user));

                //result.data = UnitWork.Find<FlowInstance>(request.page, request.limit, "CreateDate descending",
                //u => u.MakerList == "1" || u.MakerList.Contains(user.User.Id)).ToList();
                result.data = (from u in fi
                               where u.MakerList == "1" || u.MakerList.Contains(user)
                               orderby u.CreateDate descending
                               select u).Skip(pageSize * (pageNum - 1)).Take(pageSize);

            }
            else if (req.type == "disposed")  //已办事项（即我参与过的流程）
            {
                //var instances = UnitWork.Find<FlowInstanceTransitionHistory>(u => u.CreateUserId == user.User.Id)
                //Select(u => u.InstanceId).Distinct();
                var instances = (from u in fo
                                 where u.CreateUserId == int.Parse(user)
                                 select u).Distinct();
                //var query = from ti in instances 
                //            join ct in fi on ti equals ct.KeyId
                //                into tmp
                //            from ct in tmp.DefaultIfEmpty()
                //            select ct;

                //    result.data = query.OrderByDescending(u => u.CreateDate)
                //        .Skip((request.page - 1) * request.limit)
                //        .Take(request.limit).ToList();
                //    result.count = instances.Count();
            }
            else  //我的流程
            {
                //result.count = UnitWork.Find<FlowInstance>(u => u.CreateUserId == user.User.Id).Count();
                //result.data = UnitWork.Find<FlowInstance>(request.page, request.limit,
                //    "CreateDate descending", u => u.CreateUserId == user.User.Id).ToList();
            }
            db.Dispose();//释放数据库连接资源
            return result;
        }

        /// <summary>
        /// 审核流程 流程处理
        /// <para>李玉宝于2017-01-20 15:44:45</para>
        /// </summary>
        public static void Verification(VerificationReq vreq)
        {
            //驳回
            if (vreq.VerificationFinally == "3")
            {
                NodeReject(vreq);
            }
            else if (vreq.VerificationFinally == "2")//表示不同意
            {
                NodeVerification(vreq.FlowInstanceId, false, vreq.VerificationOpinion);
            }
            else if (vreq.VerificationFinally == "1")//表示同意
            {
                NodeVerification(vreq.FlowInstanceId, true, vreq.VerificationOpinion);
            }
        }

        /// <summary>
        /// 节点审核
        /// </summary>
        /// <param name="instanceId"></param>
        /// <returns></returns>
        public static bool NodeVerification(string instanceId, bool flag, string description = "")
        {
            string VerificationFinally = "1";//审核类型1同意2不同意3驳回
            if (!flag)
            {
                VerificationFinally = "2";
            }

            SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            try
            {
                FlowInstanceModel flowInstance = DbUtils.Get<FlowInstanceModel>(long.Parse(instanceId));
                FlowInstanceOperationHistoryModel flowInstanceOperationHistory = new FlowInstanceOperationHistoryModel();
                flowInstanceOperationHistory.InstanceId = int.Parse(instanceId);
                flowInstanceOperationHistory.CreateUserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                flowInstanceOperationHistory.CreateUserName = SysVisitor.Instance.cookiesUserName;
                flowInstanceOperationHistory.CreateDate = DateTime.Now;
                flowInstanceOperationHistory.VerificationFinally = VerificationFinally;//审核类型
                flowInstanceOperationHistory.VerificationOpinion = description;//审核意见
                FlowRuntime wfruntime = new FlowRuntime(flowInstance);

                

                var tag = new Tag
                {
                    UserName = SysVisitor.Instance.cookiesUserName,
                    UserId = SysVisitor.Instance.cookiesUserId,
                    Description = description
                };
                #region 会签
                if (flowInstance.ActivityType == 0)//当前节点是会签节点
                {
                    tag.Taged = 1;
                    wfruntime.MakeTagNode(wfruntime.runtimeModel.currentNodeId, tag);//标记会签节点状态

                    string verificationNodeId = ""; //寻找当前登陆用户可审核的节点Id
                    List<string> nodelist = wfruntime.GetCountersigningNodeIdList(wfruntime.runtimeModel.currentNodeId);
                    foreach (string item in nodelist)
                    {
                        var makerList = GetMakerList(wfruntime.runtimeModel.nodes[item]
                            , (wfruntime.runtimeModel.flowInstanceId).ToString());
                        if (makerList == "-1") continue;

                        //if (makerList.Split(',').Any(one => SysVisitor.Instance.cookiesUserId == one))
                        //{
                        //    verificationNodeId = item;
                        //}
                        verificationNodeId = item;
                        if (verificationNodeId != "")
                        {
                            if (flag)
                            {
                                tag.Taged = 1;
                                flowInstanceOperationHistory.Content = "【" + wfruntime.runtimeModel.nodes[verificationNodeId].name + "】【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "】同意,备注：" + description;
                                flowInstanceOperationHistory.NodeName = wfruntime.runtimeModel.nodes[verificationNodeId].name;
                            }
                            else
                            {
                                tag.Taged = -1;
                                flowInstanceOperationHistory.Content = "【" + wfruntime.runtimeModel.nodes[verificationNodeId].name + "】【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "】不同意,备注：" + description;
                                flowInstanceOperationHistory.NodeName = wfruntime.runtimeModel.nodes[verificationNodeId].name;
                            }

                            wfruntime.MakeTagNode(verificationNodeId, tag);//标记审核节点状态
                            string confluenceres = wfruntime.NodeConfluence(verificationNodeId, tag);
                            switch (confluenceres)
                            {
                                case "-1"://不通过
                                    flowInstance.IsFinish = 3;
                                    break;
                                case "1"://等待，当前节点还是会签开始节点，不跳转
                                    break;
                                default://通过
                                    flowInstance.PreviousId = flowInstance.ActivityId;
                                    flowInstance.ActivityId = wfruntime.runtimeModel.nextNodeId;
                                    flowInstance.ActivityType = wfruntime.runtimeModel.nextNodeType;//-1无法运行,0会签开始,1会签结束,2一般节点,4流程运行结束
                                    flowInstance.ActivityName = wfruntime.runtimeModel.nextNode.name;
                                    flowInstance.IsFinish = (wfruntime.runtimeModel.nextNodeType == 4 ? 1 : 0);
                                    flowInstance.MakerList = (wfruntime.runtimeModel.nextNodeType == 4 ? "" : GetMakerList(wfruntime));//当前节点可执行的人信息

                                    #region 流转记录
                                    FlowInstanceTransitionHistoryModel fth = new FlowInstanceTransitionHistoryModel();
                                    fth.InstanceId = flowInstance.KeyId;
                                    fth.CreateUserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                                    fth.CreateUserName = SysVisitor.Instance.cookiesUserName;
                                    fth.FromNodeId = wfruntime.runtimeModel.currentNodeId;
                                    fth.FromNodeName = wfruntime.runtimeModel.currentNode.name;
                                    fth.FromNodeType = wfruntime.runtimeModel.currentNodeType;
                                    fth.ToNodeId = wfruntime.runtimeModel.nextNodeId;
                                    fth.ToNodeName = wfruntime.runtimeModel.nextNode.name;
                                    fth.ToNodeType = wfruntime.runtimeModel.nextNodeType;
                                    fth.IsFinish = wfruntime.runtimeModel.nextNodeType == 4 ? 1 : 0;
                                    fth.TransitionSate = 0;
                                    #endregion
                                    DbUtils.tranInsert(fth, tran);

                                    break;
                            }
                        }
                        else
                        {
                            throw (new Exception("审核异常,找不到审核节点"));
                        }
                        flowInstance.SchemeContent = JsonConvert.SerializeObject(wfruntime.runtimeModel.schemeContentJson);
                        DbUtils.tranUpdate(flowInstance, tran, null);
                        DbUtils.tranInsert(flowInstanceOperationHistory, tran);
                        #region 微信催单

                        string[] codesx = flowInstance.Code.Split('_');
                        //string[] names = flowInstance.CustomName.Split('_');

                        sendWxContent wxcx = new sendWxContent();
                        wxcx.first = flowInstance.CustomName + "通知";
                        wxcx.keyword1 = "JYD" + codesx[0];
                        wxcx.keyword2 = flowInstanceOperationHistory.CreateUserName + "已完成:" + wfruntime.runtimeModel.currentNode.name + ",您要完成:" + wfruntime.runtimeModel.nextNode.name;//当前流程
                        wxcx.keyword3 = DateTime.Now.ToString();
                        wxcx.remark = "流程创建人:" + flowInstance.CreateUserName + ",意见:" + description;
                        wxcx.userids = flowInstance.MakerList;
                        wxcx.viewUrl = NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/QRCodeView.aspx?keyid=" + codesx[1] + "";
                        sendWeixin.sendWX(wxcx);//发送微信

                        #endregion
                        tran.Commit();


                        return true;
                    }

                    //if (verificationNodeId != "")
                    //{
                    //    if (flag)
                    //    {
                    //        tag.Taged = 1;
                    //        flowInstanceOperationHistory.Content = "【" + wfruntime.runtimeModel.nodes[verificationNodeId].name + "】【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "】同意,备注：" + description;
                    //        flowInstanceOperationHistory.NodeName = wfruntime.runtimeModel.nodes[verificationNodeId].name;
                    //    }
                    //    else
                    //    {
                    //        tag.Taged = -1;
                    //        flowInstanceOperationHistory.Content = "【" + wfruntime.runtimeModel.nodes[verificationNodeId].name + "】【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "】不同意,备注：" + description;
                    //        flowInstanceOperationHistory.NodeName = wfruntime.runtimeModel.nodes[verificationNodeId].name;
                    //    }

                    //    wfruntime.MakeTagNode(verificationNodeId, tag);//标记审核节点状态
                    //    string confluenceres = wfruntime.NodeConfluence(verificationNodeId, tag);
                    //    switch (confluenceres)
                    //    {
                    //        case "-1"://不通过
                    //            flowInstance.IsFinish = 3;
                    //            break;
                    //        case "1"://等待，当前节点还是会签开始节点，不跳转
                    //            break;
                    //        default://通过
                    //            flowInstance.PreviousId = flowInstance.ActivityId;
                    //            flowInstance.ActivityId = wfruntime.runtimeModel.nextNodeId;
                    //            flowInstance.ActivityType = wfruntime.runtimeModel.nextNodeType;//-1无法运行,0会签开始,1会签结束,2一般节点,4流程运行结束
                    //            flowInstance.ActivityName = wfruntime.runtimeModel.nextNode.name;
                    //            flowInstance.IsFinish = (wfruntime.runtimeModel.nextNodeType == 4 ? 1 : 0);
                    //            flowInstance.MakerList = (wfruntime.runtimeModel.nextNodeType == 4 ? "" : GetMakerList(wfruntime));//当前节点可执行的人信息

                    //            #region 流转记录
                    //            FlowInstanceTransitionHistoryModel fth = new FlowInstanceTransitionHistoryModel();
                    //            fth.InstanceId = flowInstance.KeyId;
                    //            fth.CreateUserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                    //            fth.CreateUserName = SysVisitor.Instance.cookiesUserName;
                    //            fth.FromNodeId = wfruntime.runtimeModel.currentNodeId;
                    //            fth.FromNodeName = wfruntime.runtimeModel.currentNode.name;
                    //            fth.FromNodeType = wfruntime.runtimeModel.currentNodeType;
                    //            fth.ToNodeId = wfruntime.runtimeModel.nextNodeId;
                    //            fth.ToNodeName = wfruntime.runtimeModel.nextNode.name;
                    //            fth.ToNodeType = wfruntime.runtimeModel.nextNodeType;
                    //            fth.IsFinish = wfruntime.runtimeModel.nextNodeType == 4 ? 1 : 0;
                    //            fth.TransitionSate = 0;
                    //            #endregion
                    //            DbUtils.tranInsert(fth, tran);

                    //            break;
                    //    }
                    //}
                    //else
                    //{
                    //    throw (new Exception("审核异常,找不到审核节点"));
                    //}
                }
                #endregion

                #region 一般审核
                else//一般审核
                {
                    
                    if (flag)
                    {
                        tag.Taged = 1;
                        wfruntime.MakeTagNode((wfruntime.runtimeModel.currentNodeId).ToString(), tag);
                        flowInstance.PreviousId = flowInstance.ActivityId;
                        flowInstance.ActivityId = wfruntime.runtimeModel.nextNodeId;
                        flowInstance.ActivityType = wfruntime.runtimeModel.nextNodeType;
                        flowInstance.ActivityName = wfruntime.runtimeModel.nextNode.name;
                        flowInstance.MakerList = wfruntime.runtimeModel.nextNodeType == 4 ? "" : GetMakerList(wfruntime);//当前节点可执行的人信息
                        flowInstance.IsFinish = (wfruntime.runtimeModel.nextNodeType == 4 ? 1 : 0);
                        #region 流转记录
                        FlowInstanceTransitionHistoryModel fth = new FlowInstanceTransitionHistoryModel();
                        fth.InstanceId = flowInstance.KeyId;
                        fth.CreateUserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        fth.CreateUserName = SysVisitor.Instance.cookiesUserName;
                        fth.FromNodeId = wfruntime.runtimeModel.currentNodeId;
                        fth.FromNodeName = wfruntime.runtimeModel.currentNode.name;
                        fth.FromNodeType = wfruntime.runtimeModel.currentNodeType;
                        fth.ToNodeId = wfruntime.runtimeModel.nextNodeId;
                        fth.ToNodeName = wfruntime.runtimeModel.nextNode.name;
                        fth.ToNodeType = wfruntime.runtimeModel.nextNodeType;
                        fth.IsFinish = wfruntime.runtimeModel.nextNodeType == 4 ? 1 : 0;
                        fth.TransitionSate = 0;
                        #endregion
                        DbUtils.tranInsert(fth, tran);

                        flowInstanceOperationHistory.NodeName = wfruntime.runtimeModel.currentNode.name;
                        flowInstanceOperationHistory.Content = "【" + wfruntime.runtimeModel.currentNode.name
                            + "】【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "】同意,备注：" + description;
                    }
                    else
                    {
                        flowInstance.IsFinish = 3; //表示该节点不同意
                        tag.Taged = -1;
                        wfruntime.MakeTagNode(wfruntime.runtimeModel.currentNodeId, tag);
                        flowInstanceOperationHistory.NodeName = wfruntime.runtimeModel.currentNode.name;
                        flowInstanceOperationHistory.Content = "【"
                            + wfruntime.runtimeModel.currentNode.name + "】【"
                            + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "】不同意,备注："
                            + description;
                    }
                }
                #endregion

                flowInstance.SchemeContent = JsonConvert.SerializeObject(wfruntime.runtimeModel.schemeContentJson);
                DbUtils.tranUpdate(flowInstance, tran, null);
                DbUtils.tranInsert(flowInstanceOperationHistory, tran);
                #region 微信催单

                string[] codes = flowInstance.Code.Split('_');
                //string[] names = flowInstance.CustomName.Split('_');

                sendWxContent wxc = new sendWxContent();
                wxc.first = flowInstance.CustomName + "通知";
                wxc.keyword1 = "JYD" + codes[0];
                wxc.keyword2 = flowInstanceOperationHistory.CreateUserName + "已完成:" + wfruntime.runtimeModel.currentNode.name + ",您要完成:" + wfruntime.runtimeModel.nextNode.name;//当前流程
                wxc.keyword3 = DateTime.Now.ToString();
                wxc.remark = "流程创建人:" + flowInstance.CreateUserName + ",意见:" + description;
                wxc.userids = flowInstance.MakerList;
                wxc.viewUrl = NetWing.Common.ConfigHelper.GetValue("website") + "/JydModleOrder/QRCodeView.aspx?keyid=" + codes[1] + "";
                sendWeixin.sendWX(wxc);//发送微信

                #endregion
                tran.Commit();
                

                return true;
            }
            catch (Exception err)
            {
                WriteLogs.WriteLogsE("Logs", "DINGDError >> caozuo", err.Message + " >>> " + err.StackTrace);
                tran.Rollback();
                throw err;
            }

        }


        /// <summary>
        /// 驳回
        /// </summary>
        /// <returns></returns>
        public static bool NodeReject(VerificationReq reqest)
        {
            SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            FlowInstanceModel flowInstance = DbUtils.Get<FlowInstanceModel>(long.Parse(reqest.FlowInstanceId));
            FlowRuntime wfruntime = new FlowRuntime(flowInstance);
            string resnode = "";
            if (string.IsNullOrEmpty(reqest.NodeRejectStep))
            {
                resnode = wfruntime.RejectNode();
            }
            else
            {
                resnode = reqest.NodeRejectStep;
            }

            var tag = new Tag
            {
                Description = reqest.VerificationOpinion,
                Taged = 0,
                UserId = SysVisitor.Instance.cookiesUserId,
                UserName = SysVisitor.Instance.cookiesUserName
            };

            wfruntime.MakeTagNode(wfruntime.runtimeModel.currentNodeId, tag);
            flowInstance.IsFinish = 4;//4表示驳回（需要申请者重新提交表单）

            try
            {
                if (resnode != "")
                {
                    flowInstance.PreviousId = flowInstance.ActivityId;
                    flowInstance.ActivityId = resnode;
                    flowInstance.ActivityType = wfruntime.GetNodeType(resnode);
                    flowInstance.ActivityName = wfruntime.runtimeModel.nodes[resnode].name;
                    flowInstance.MakerList = GetMakerList(wfruntime.runtimeModel.nodes[resnode], flowInstance.PreviousId);//当前节点可执行的人信息
                    #region 流转记录

                    FlowInstanceTransitionHistoryModel fth = new FlowInstanceTransitionHistoryModel();
                    fth.InstanceId = flowInstance.KeyId;
                    fth.CreateUserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                    fth.CreateUserName = SysVisitor.Instance.cookiesUserName;
                    fth.FromNodeId = wfruntime.runtimeModel.currentNodeId;
                    fth.FromNodeName = wfruntime.runtimeModel.currentNode.name;
                    fth.FromNodeType = wfruntime.runtimeModel.currentNodeType;
                    fth.ToNodeId = wfruntime.runtimeModel.nextNodeId;
                    fth.ToNodeName = wfruntime.runtimeModel.nextNode.name;
                    fth.ToNodeType = wfruntime.runtimeModel.nextNodeType;
                    fth.IsFinish = wfruntime.runtimeModel.nextNodeType == 4 ? 1 : 0;
                    fth.TransitionSate = 1;
                    DbUtils.tranInsert(fth, tran);


                    #endregion
                }
                DbUtils.tranUpdate(flowInstance, tran, null);
                FlowInstanceOperationHistoryModel foh = new FlowInstanceOperationHistoryModel();
                foh.InstanceId = int.Parse(reqest.FlowInstanceId);
                foh.CreateUserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                foh.CreateUserName = SysVisitor.Instance.cookiesUserName;
                foh.CreateDate = DateTime.Now;
                foh.Content = "【"
                              + wfruntime.runtimeModel.currentNode.name
                              + "】【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "】驳回,备注："
                              + reqest.VerificationOpinion;
                tran.Commit();
            }
            catch (Exception e)
            {
                tran.Rollback();
                throw;
            }



            return true;
        }

    }



}